package com.cn.esermis.utils;

import com.alibaba.fastjson2.JSONObject;
import com.cn.esermis.coding.PollutionGas;
import com.cn.esermis.constant.Constant;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author DaHuaJia
 * @Description HJ212消息数据处理
 * HJ212数据示例：##0746ST=31;CN=2061;PW=123456;MN=7568770259402;Flag=0;CP=&&DataTime=20221008100000;B02-Min=1.6960,B02-Avg=3.0586,B02-Max=3.7704,B02-Cou=11010.8437;S01-Min=17.7469,S01-Avg=19.4636,S01-Max=19.6944;S02-Min=3.2459,S02-Avg=5.6705,S02-Max=6.9578;S03-Min=30.0434,S03-Avg=30.2675,S03-Max=30.4503;S08-Min=-0.4643,S08-Avg=-0.3541,S08-Max=0.0000;S05-Min=6.1814,S05-Avg=6.8655,S05-Max=7.0097;a24088-Min=2.4957,a24088-Avg=3.2176,a24088-Max=4.7744,a24088-Cou=0.0354;25-Min=6.4292,25-Avg=12.1457,25-Max=20.0606,25-Cou=0.1336;a05002-Min=2.7715,a05002-Avg=7.8561,a05002-Max=14.7934,a05002-Cou=0.0863;17-Min=0.0000,17-Avg=0.0000,17-Max=0.0000,17-Cou=0.0000;18-Min=0.0000,18-Avg=0.0000,18-Max=0.0000,18-Cou=0.0000;16-Min=0.0000,16-Avg=0.0000,16-Max=0.0000,16-Cou=0.0000&&7BC0
 * @Date 2022-10-09 11:09:16
 */
@Slf4j
public class HJ212MsgUtils {

    /**
     * 传入HJ212数据，返回简单json数据，没有对污染源进行分类汇总。
     *
     * @param msg hj212
     * @return json
     */


    public static JSONObject dealMsg1(String msg) {
        JSONObject data = new JSONObject();
        try {
            // 拆分消息
            String[] subMsg = msg.split("&&");

            // 清洗消息头基本数据
            String headStr = subMsg[0].substring(2).replace(";CP=", "").replace("=", "\":\"")
                    .replace(",", "\",\"").replace(";", "\",\"");
            data.put("SIZE", headStr.substring(0, 4));
            data.putAll(JSONObject.parseObject("{\"" + headStr.substring(4) + "\"}"));

            // 清洗数据体基本数据
            String paramStr = subMsg[1].replace("=", "\":\"").replace(",", "\",\"")
                    .replace(";", "\",\"");
            data.put("CP", JSONObject.parseObject("{\"" + paramStr + "\"}"));

            // 保存消息尾数据，主要是CRC校验和包结束符
            data.put("End", subMsg[2]);

        } catch (Exception e) {
            log.error("HJ212数据转JSON错误。报错信息：{}，消息内容：{}", e.getMessage(), msg);
            e.printStackTrace();
        }
        return data;
    }


    /**
     * 传入HJ212数据，返回复杂json数据，对污染源进行分类汇总，不同污染源用不同的json key。
     *
     * @param msg hj212
     * @return json
     */
    public static JSONObject dealMsg2(String msg) {
        if (msg.contains("CN=2011")){
            return null;
        }
        JSONObject data = new JSONObject();
        try {
            // 拆分消息
            String[] subMsg = msg.split("&&");

            // 清洗消息头基本数据
            String headStr = subMsg[0].substring(2).replace(";CP=", "").replace("=", "\":\"")
                    .replace(",", "\",\"").replace(";", "\",\"");
            data.put("SIZE", headStr.substring(0, 4));
            data.putAll(JSONObject.parseObject("{\"" + headStr.substring(4) + "\"}"));
            if (!Constant.COMMAND.contains(data.getString("CN"))) {
                return null;
            }
            // 清洗数据体基本数据
            String[] monitors = subMsg[1].split(";");
            List<JSONObject> cp = new LinkedList<>();
            for (String obj : monitors) {
                String paramStr = obj.replace("=", "\":\"").replace(",", "\",\"")
                        .replace(";", "\",\"");
                // 如果是时间信息，则直接放到外层
                if (paramStr.contains("DataTime")) {
                    data.putAll(JSONObject.parseObject("{\"" + paramStr + "\"}"));
                } else if (paramStr.contains("PNUM")) {
                    data.putAll(JSONObject.parseObject("{\"" + paramStr + "\"}"));
                } else if (paramStr.contains("PNO")) {  //PNO
                    data.putAll(JSONObject.parseObject("{\"" + paramStr + "\"}"));
                } else {
                    String[] ele = getPollutionSource(paramStr);
                    JSONObject jsonObject = JSONObject.parseObject("{\"" + ele[1] + "\"}");
                    PollutionGas[] values = PollutionGas.values();
                    jsonObject.put("factor", ele[0]);
                    if (ele[0].length() < 6){
                        for (PollutionGas value : values) {
                            if (value.oldCode().equals(ele[0])) {
                                jsonObject.put("factor", value.code());
                                break;
                            }
                        }
                    }
                    cp.add(jsonObject);
                }
            }
            // 处理有相同因子 值不同的数据
            Set<JSONObject> cpNew = new HashSet<>();
            for (JSONObject jsonObject : cp) {
                JSONObject cpd = new JSONObject();
                List<JSONObject> collect = cp.stream().filter(d -> d.getString("factor").equals(jsonObject.getString("factor"))).collect(Collectors.toList());
//                System.out.println(collect);
                for (JSONObject object : collect) {
                    cpd.putAll(object);
                }
                cpNew.add(cpd);
            }



            data.put("CP", cpNew);


            // 保存消息尾数据，主要是CRC校验和包结束符
            data.put("End", subMsg[2]);

        } catch (Exception e) {
            log.error("HJ212数据转JSON错误。报错信息：{}，消息内容：{}", e.getMessage(), msg);
            e.printStackTrace();
        }
        return data;
    }


    /**
     * 接收数据后做数据格式化，回复数据是否接收成功
     * 消息回复
     */
    public static String reply(String msg) {
        StringBuilder result = new StringBuilder();
        JSONObject data = new JSONObject();
        try {
            // 拆分消息
            String[] subMsg = msg.split("&&");

            // 清洗消息头基本数据
            String headStr = subMsg[0].substring(2).replace(";CP=", "").replace("=", "\":\"")
                    .replace(",", "\",\"").replace(";", "\",\"");
            data.put("SIZE", headStr.substring(0, 4));
            data.putAll(JSONObject.parseObject("{\"" + headStr.substring(4) + "\"}"));
            for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
                if (stringObjectEntry.getKey().equals("SIZE"))
                    continue;
                if (stringObjectEntry.getKey().equals("CN")){
                    result.append(stringObjectEntry.getKey()).append("=").append("9014").append(";");
                }else
                if (stringObjectEntry.getKey().equals("ST")){
                    result.append(stringObjectEntry.getKey()).append("=").append("91").append(";");
                }else
                if (stringObjectEntry.getKey().equals("Flag")){
                    result.append(stringObjectEntry.getKey()).append("=").append("4").append(";");
                }else{
                    result.append(stringObjectEntry.getKey()).append("=").append(stringObjectEntry.getValue()).append(";");
                }
            }
        } catch (Exception e) {
            log.error("HJ212数据转JSON错误。报错信息：{}，消息内容：{}", e.getMessage(), msg);
        }
        return result.toString()+"CP=&&&&";
    }




    /**
     * 解析污染源数据，获取污染源编号
     */
    private static String[] getPollutionSource(String data) {
        if (data.contains("-")) {
            String key = data.substring(0, data.indexOf("-"));
            data = data.replaceAll(key + "-", "");

            String[] result = new String[2];
            result[0] = key;
            result[1] = data;
            return result;
        } else {
            if (data.contains(":")) {
                String[] split = data.split(":");
                return split;
            }

            return new String[]{data};
        }

    }


    public static void main(String[] args) {
        System.out.println(reply("##0458QN=20240828051005127;ST=32;CN=2051;PW=123456;MN=120119BHHBS001;Flag=4;CP=&&DataTime=20240828050000;w01018-Min=13.887,w01018-Max=13.887,w01018-Avg=13.887,w01018-Cou=0,w01018-Flag=N;w21003-Min=6.679,w21003-Max=6.679,w21003-Avg=6.679,w21003-Cou=0,w21003-Flag=N;w00000-Min=0,w00000-Max=0,w00000-Avg=0,w00000-Cou=0,w00000-Flag=N;w01001-Min=6.215,w01001-Max=6.309,w01001-Avg=6.266,w01001-Flag=N;w01010-Min=31.432,w01010-Max=31.464,w01010-Avg=31.445g=N&&8BC1"));
//        System.out.println(dealMsg2("##1458QN=20240827155628777;ST=31;CN=2061;PW=123456;MN=120119ZHSYQ081;Flag=5;CP=&&DataTime=20240827150000;a00000-Min=0.01,a00000-Max=0.08,a00000-Avg=0.04,a00000-Cou=135.34,a00000-Flag=N;a19001-Min=19.92,a19001-Max=20.01,a19001-Avg=19.95,a19001-Cou=0,a19001-Flag=N;a01011-Min=0.09,a01011-Max=0.47,a01011-Avg=0.22,a01011-Cou=0,a01011-Flag=N;a01012-Min=34.81,a01012-Max=36.07,a01012-Avg=35.4,a01012-Cou=0,a01012-Flag=N;a01013-Min=-35.42,a01013-Max=-20,a01013-Avg=-25.03,a01013-Cou=0,a01013-Flag=N;a01014-Min=1.75,a01014-Max=2.33,a01014-Avg=2.21,a01014-Cou=0,a01014-Flag=N;a34013-Min=0.13,a34013-Max=0.19,a34013-Avg=0.15,a34013-Cou=0,a34013-ZsMin=1.17,a34013-ZsMax=1.85,a34013-ZsAvg=1.45,a34013-Flag=N;a21026-Min=0.07,a21026-Max=0.35,a21026-Avg=0.17,a21026-Cou=0,a21026-ZsMin=0.63,a21026-ZsMax=3.31,a21026-ZsAvg=1.66,a21026-Flag=N;a21002-Min=0.04,a21002-Max=0.37,a21002-Avg=0.17,a21002-Cou=0,a21002-ZsMin=0.35,a21002-ZsMax=3.45,a21002-ZsAvg=1.61,a21002-Flag=N;a21005-Min=0,a21005-Max=1.2,a21005-Avg=0.73,a21005-Cou=0,a21005-ZsMin2,a05001-Cou=0,a05001-ZsMin=0.19,a05001-ZsMax=0.27,a05001-ZsAvg=0.21,a05001-Flag=N&&CB81"));
    }

}

